package org.ediba.siri.web.rest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ediba.siri.core.image.domain.ImageAlbum;
import org.ediba.siri.core.image.service.ImageService;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.ResponseBody;

public class ImageAlbumController extends Controller {
	
	private ImageService imageService;
	public void setImageService(ImageService imageService) {this.imageService = imageService;}
	
	@ResponseBody
	public Map<String,Object> postHandler(HttpServletRequest request, HttpServletResponse response, ImageAlbumCommand imageAlbumCommand){
		
		ImageAlbum imageAlbum = this.imageService.albumCreate();
		imageAlbum.setName(imageAlbumCommand.getName());
		imageAlbum = this.imageService.albumUpdate(imageAlbum);
		
		Map<String,Object> _result = new HashMap<String,Object>(2);
		_result.put("data", imageAlbum);
		_result.put("success", true);
		return _result;
	}
	
	@ResponseBody
	public Map<String,Object> getHandler(HttpServletRequest request, HttpServletResponse response){

		List<ImageAlbum> imageAlbums = this.imageService.albumRetrieve();
		
		Map<String,Object> _result = new HashMap<String,Object>(4);
		_result.put("data", imageAlbums);
		_result.put("total", imageAlbums.size());
		_result.put("success", true);
		_result.put("message", "OK");
		return _result;
	}
	
	@ResponseBody
	public Map<String,Object> putHandler(HttpServletRequest request, HttpServletResponse response, ImageAlbumCommand command) throws ServletRequestBindingException{
		Boolean add = ServletRequestUtils.getBooleanParameter(request, "add");
		
		ImageAlbum imageAlbum = this.imageService.albumRetrieve(command.getId());
		if (command.getName() != null)
			imageAlbum.setName(command.getName());
		if ((add != null) && (command.getIdsImage() != null)){
			for (Integer _idImage : command.getIdsImage()) {
				if (add)
					imageAlbum.getImages().add(this.imageService.retrieve(_idImage));
				else
					imageAlbum.getImages().remove(this.imageService.retrieve(_idImage));				
			}
		}
		imageAlbum = this.imageService.albumUpdate(imageAlbum);
			
		Map<String,Object> _result = new HashMap<String,Object>(2);
		_result.put("success", true);
		_result.put("data", imageAlbum);
		return _result;
	}
	
	@ResponseBody
	public Map<String,Object> deleteHandler(HttpServletRequest request, HttpServletResponse response, ImageAlbumCommand imageAlbumCommand){
		
		this.imageService.albumDelete(imageAlbumCommand.getId());
		
		Map<String,Object> _result = new HashMap<String,Object>(1);
		_result.put("success", true);
		return _result;
	}
	
}
